﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using DunLibrary.Client;
using DunSilverlight.Comm;
using DunLibrary.Query;
using DunLibrary.Dun;
using Telerik.Windows.Controls;

namespace DunSilverlight.Views
{
    /// <summary>
    /// 任务分配
    /// </summary>
    public partial class CollectionTaskAllot : Page
    {
        private const int PageSize = 19;

        private QueryCondition queryCondition = null;


        public CollectionTaskAllot()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(CollectionTaskAllot_Loaded);
        }

        void CollectionTaskAllot_Loaded(object sender, RoutedEventArgs e)
        {
            cmbPeriod.ItemsSource = AppGlobal.Periods;

            AppGlobal.GetBanks((IList<Company> banks) =>
                {
                    cmbBank.ItemsSource = banks;
                });

            AppGlobal.GetControlTypes((IList<ControlType> controls) =>
            {
                cmbControlType.ItemsSource = controls;
            });
            LoadCompany();
            LoadOpers();
            LoadOpersWithInfo();
        }

        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

        }

        /// <summary>
        /// 通过权限设置界面控制
        /// </summary>
        private void SetControlByRight()
        {

        }
        /// <summary>
        /// 开始查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Allot_Case))
            {
                Tools.ShowMessage("您没有分配委案的权限", "", false);
                return;
            }

            BuildHql();

            queryCondition.FirstResult = 0;

            QueryPaging(queryCondition);
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="frist"></param>
        /// <param name="max"></param>
        private void QueryPaging(QueryCondition qc)
        {
            if (qc != null)
            {
                CaseService.CaseServiceClient ser = new CaseService.CaseServiceClient();

                //查询结束的事件
                ser.GetListByHQLWithPagingCompleted += (object sender, CaseService.GetListByHQLWithPagingCompletedEventArgs e) =>
                {
                    ser.GetCustomDataByHqlCompleted += (object sender1, CaseService.GetCustomDataByHqlCompletedEventArgs e1) =>
                    {
                        try
                        {
                            int total = 0;
                            IList<Case> cases = JsonSerializerHelper.JsonToEntities<Case>(e.Result, out total);

                            dgdCase.ItemsSource = cases;
                            rdpCase.ItemCount = total;

                            var tb = dgdCase.Columns[2].Footer as TextBlock;
                            if (tb != null)
                                tb.Text = string.Format("{0}", total);

                            double totalAmount = JsonSerializerHelper.JsonToEntity<double>(e1.Result);
                            tb = dgdCase.Columns[5].Footer as TextBlock;
                            if (tb != null)
                                tb.Text = totalAmount.ToString();
                        }
                        catch (Exception ex)
                        {
                            Tools.ShowMessage(ex.Message, "", false);//这里会出错，应该是分页控件的问题
                        }
                        finally
                        {
                            ser.CloseAsync();
                        }
                    };
                    ser.GetCustomDataByHqlAsync(totalAmountHql);

                };

                string condition = Newtonsoft.Json.JsonConvert.SerializeObject(qc);

                ser.GetListByHQLWithPagingAsync(condition);
            }
        }

        //查询符合条件的所有记录的金额总和
        string totalAmountHql = string.Empty;


        /// <summary>
        /// 根据选择条件生成查询的hql
        /// </summary>
        /// <returns></returns>
        private void BuildHql()
        {
            //string hql = "from Case as c inner join c.ArrearRecords as a inner join c.Holder.Contacts as t where c.Catalog.IsFinish=false";
            string hql = "from Case as c where c.Catalog.IsFinish=false";
            string where = null;

            if (!string.IsNullOrEmpty(txtYear.Text.Trim()))
            {
                where = " and c.Year=" + txtYear.Text;//年
            }

            if (cmbPeriod.SelectedItem != null)
            {
                where += " and c.Period=" + cmbPeriod.SelectedItem.ToString();//期
            }

            if (timeImport.SelectedDate != null)
            {
                where += " and year(c.Catalog.ImportTime)*10000+month(c.Catalog.ImportTime)*100+day(c.Catalog.ImportTime)=" + timeImport.SelectedDate.Value.ToString("yyyyMMdd");
            }

            if (cmbBank.SelectedItem != null)//银行
            {
                DunLibrary.Client.Company bank = cmbBank.SelectedItem as DunLibrary.Client.Company;
                where += " and c.Bank.Id=" + bank.Id;
            }

            if (!string.IsNullOrEmpty(txtBranch.Text.Trim()))
            {
                where += string.Format(" and exists (from ArrearRecord as a where a.Case.Id=c.Id and a.BranchName Like '{0}%')", txtBranch.Text.Trim());
                //where += " and a.BranchName='" + txtBranch.Text.Trim() + "'";
            }

            if (!string.IsNullOrEmpty(txtCardType.Text.Trim()))
            {
                where += string.Format(" and exists (from ArrearRecord as a where a.Case.Id=c.Id and a.Card.CardType = '{0}')", txtBranch.Text.Trim());
                //where += " and a.Card.CardType='" + txtBranch.Text.Trim() + "'";
            }

            if (!string.IsNullOrEmpty(txtAccount.Text.Trim()))
            {
                where += string.Format(" and exists (from ArrearRecord as a where a.Case.Id=c.Id and a.Card.AccountNo = '{0}')", txtAccount.Text.Trim());
                //where += " and a.Card.AccountNo='" + txtAccount.Text.Trim() + "'";
            }

            if (!string.IsNullOrEmpty(txtHolder.Text.Trim()))
            {
                where += " and c.Holder.Name='" + txtHolder.Text.Trim() + "'";
            }

            if (!string.IsNullOrEmpty(txtIdCard.Text.Trim()))
            {
                where += " and c.Holder.Number='" + txtIdCard.Text.Trim() + "'";
            }

            //if (!string.IsNullOrEmpty(txtPhone.Text.Trim()))
            //{
            //    where += string.Format(" and exists (from CardholderContact as hc where hc.Owner.Id=c.Holder.Id and hc.Content Like '{0}%')", txtPhone.Text.Trim());
            //    //where += " and t.Content like '" + txtPhone.Text.Trim() + "%'";
            //}

            if (!string.IsNullOrEmpty(txtMinArrear.Text.Trim()))
            {
                double d1 = 0;
                if (double.TryParse(txtMinArrear.Text.Trim(), out d1))
                {
                    where += " and c.TotalAmount >=" + d1;
                }
            }

            if (!string.IsNullOrEmpty(txtMaxArrear.Text.Trim()))
            {
                double d1 = 0;
                if (double.TryParse(txtMaxArrear.Text.Trim(), out d1))
                {
                    where += " and c.TotalAmount <=" + d1;
                }
            }



            if (!string.IsNullOrEmpty(txtCardDelayLevel1.Text.Trim()))
            {
                where += string.Format(" and c.CardDelayLevel >= '{0}' ", txtCardDelayLevel1.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtCardDelayLevel2.Text.Trim()))
            {
                where += string.Format(" and c.CardDelayLevel <= '{0}' ", txtCardDelayLevel2.Text.Trim());
            }

            DunLibrary.Organization.Organization org = cmbCompany.SelectedItem as DunLibrary.Organization.Organization;

            if (org != null && org.Parent != null)
            {
                // where += " and c.BranchCompany.Id=" + org.Id;
                where += string.Format(" and (c.BranchCompany.Id = {0} or c.BranchCompany.FullNumber like '{1}.%' )",
                    org.Id, org.FullNumber);
            }

            DunLibrary.User.User u = cmbOper.SelectedItem as DunLibrary.User.User;
            if (u != null)
            {
                where += " and c.Oper.Id=" + u.Id;
            }

            DunLibrary.Dun.ControlType ct = cmbControlType.SelectedItem as DunLibrary.Dun.ControlType;

            if (ct != null)
            {
                where += " and c.ControlType.Id=" + ct.Id;
            }

            hql += where;

            //查询金额总和的hql
            totalAmountHql = "select sum(TotalAmount)" + hql;

            //进行快速分配的hql
            quickAllocHql = hql;

            queryCondition = new QueryCondition();

            queryCondition.HQL = "select c " + hql;
            queryCondition.TotalHQL = "select count(c) " + hql;

            queryCondition.MaxResults = PageSize;

        }

        private void LoadOpersWithInfo()
        {

            UserService.UserServiceClient ser = new UserService.UserServiceClient();

            ser.GetListBySQLCompleted += (object sender, UserService.GetListBySQLCompletedEventArgs e) =>
            {
                int totalCount = 0;

                IList<object> infos = JsonSerializerHelper.JsonToEntities<object>(e.Result, out totalCount);
                dgdUser.ItemsSource = infos;
            };
            string sql = string.Format(
                        @" select u.Id,u.Name,COUNT(c.Id),cast(SUM(c.totalamount) as varchar(20))as aaa 
                            from User_User as u 
	                        left join Dun_Case as c on c.OperId=u.Id 
	                        left join User_Role as r on u.RoleId=r.Id
                            where 
                                u.isused=1  and 
                                u.OrganizationId={0} and 
                                exists(select 1 from User_Role_Right as rr 
					                        inner join User_Right as ur on rr.RightId=ur.Id 
				                        where ur.Number='process_case' and
					            rr.RoleId=r.Id) 
                            group by u.Id,u.Name", AppGlobal.CurrentUser.Organization.Id);

            ser.GetListBySQLAsync(sql);

        }

        private void LoadCompany()
        {



            IList<DunLibrary.Organization.Organization> ls;

            if (AppGlobal.CurrentUser.Organization.Parent == null)//表示总公司
            {
                Action<IList<DunLibrary.Organization.Organization>> getOrgCallBack = (IList<DunLibrary.Organization.Organization> orgs) =>
                {

                    ls = orgs;
                    cmbCompany.ItemsSource = ls;
                    cmbCompany.IsEnabled = true;
                };
                AppGlobal.GetOrganizations(getOrgCallBack);

            }
            else
            {
                ls = new List<DunLibrary.Organization.Organization>();
                ls.Add(AppGlobal.CurrentUser.Organization);
                cmbCompany.ItemsSource = ls;
                cmbCompany.SelectedItem = ls[0];
                cmbCompany.IsEnabled = false;
            }
        }

        /// <summary>
        /// 根据权限加载业务员
        /// </summary>
        private void LoadOpers()
        {
            IList<DunLibrary.User.User> users = null;

            if (RightManagement.VerifyRight(RightManagement.Right_View_All_Case))
            {
                UserService.UserServiceClient ser = new UserService.UserServiceClient();

                ser.GetListByHQLCompleted += (object sender, UserService.GetListByHQLCompletedEventArgs e) =>
                    {
                        int totalCount = 0;
                        users = JsonSerializerHelper.JsonToEntities<DunLibrary.User.User>(e.Result, out totalCount);
                        cmbOper.ItemsSource = users;
                    };
                string hql = null;

                if (AppGlobal.CurrentUser.Organization.Parent == null)//表示总公司
                    hql = "from User "; //查询所有的用户(业务员)
                else
                    //这里有个问题，当层级超过2层的时候，不能查询子机构的用户
                    hql = "from User where Organization.Id=" + AppGlobal.CurrentUser.Organization.Id;//查询当前部门的业务员

                ser.GetListByHQLAsync(hql);
            }
            else
            {
                users = new List<DunLibrary.User.User>();
                users.Add(AppGlobal.CurrentUser);

                cmbOper.ItemsSource = users;
                cmbOper.SelectedIndex = 0;
                cmbOper.IsEnabled = false;
            }

        }


        private void rdpCase_PageIndexChanged(object sender, Telerik.Windows.Controls.PageIndexChangedEventArgs e)
        {
            if (queryCondition != null)
            {
                queryCondition.FirstResult = e.NewPageIndex * PageSize;

                QueryPaging(queryCondition);
            }
        }
        /// <summary>
        /// 分配委案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAllot_Click(object sender, RoutedEventArgs e)
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Allot_Case))
            {
                Tools.ShowMessage("您没有分配委案的权限", "", false);
                return;
            }


            if (dgdCase.SelectedItems.Count > 0)
            {
                if (dgdUser.SelectedItems.Count == 0)
                {
                    Tools.ShowMessage("请选择业务员", "", false);
                    return;
                }

                IList<int> caseIds = new List<int>();
                foreach (var item in dgdCase.SelectedItems)
                {
                    DunLibrary.Dun.Case c = item as DunLibrary.Dun.Case;
                    if (c != null && c.Oper == null)
                    {
                        caseIds.Add(c.Id);
                    }
                }
                if (caseIds.Count == 0)
                {

                    Tools.ShowMessage("当前选择的案件已经被全部分配，请重新选择未分配的案件！", "", false);
                    return;
                }

                IList<int> operIds = new List<int>();
                foreach (var item in dgdUser.SelectedItems)
                {
                    dynamic o = item;
                    int id = o[0];
                    operIds.Add(id);
                }
                CaseService.CaseServiceClient ser = new CaseService.CaseServiceClient();
                ser.QuickAllocCaseWithCaseIdsCompleted += (object sender2, CaseService.QuickAllocCaseWithCaseIdsCompletedEventArgs e2) =>
                {

                    QueryPaging(queryCondition);
                    LoadOpersWithInfo();

                    Tools.ShowMessage(string.Format("{0}个委案成功分配给{1}个操作员!", caseIds.Count, operIds.Count),
                        "", true);

                };

                ser.QuickAllocCaseWithCaseIdsAsync(Newtonsoft.Json.JsonConvert.SerializeObject(caseIds), Newtonsoft.Json.JsonConvert.SerializeObject(operIds));
            }
            else
            {
                if (dgdCase.Items.Count == 0)
                {
                    Tools.ShowMessage("没有数据，请进行查询！", "", false);
                    return;
                }

                if (dgdUser.SelectedItems.Count == 0)
                {
                    Tools.ShowMessage("请选择业务员", "", false);
                    return;
                }

                //判断是否符合当前条件的案件都已经被分配
                CaseService.CaseServiceClient ser = new CaseService.CaseServiceClient();
                ser.GetCustomDataByHqlCompleted += (object sender1, CaseService.GetCustomDataByHqlCompletedEventArgs e1) =>
                {
                    int count = JsonSerializerHelper.JsonToEntity<int>(e1.Result);
                    if (count == 0)
                    {

                        Tools.ShowMessage("符合当前条件的案件已经被全部分配，请重新指定条件！", "", false);
                        return;
                    }

                    IList<int> ids = new List<int>();
                    foreach (var item in dgdUser.SelectedItems)
                    {
                        dynamic o = item;
                        int id = o[0];
                        ids.Add(id);
                    }
                    ser.QuickAllocCaseCompleted += (object sender2, CaseService.QuickAllocCaseCompletedEventArgs e2) =>
                    {
                        count = JsonSerializerHelper.JsonToEntity<int>(e1.Result);

                        QueryPaging(queryCondition);
                        LoadOpersWithInfo();

                        Tools.ShowMessage(string.Format("{0}个委案成功分配给{1}个操作员!", count, ids.Count),
                            "", true);

                    };

                    string hql1 = string.Format("select Id {0} and c.Oper is null order by c.TotalAmount desc", quickAllocHql);
                    ser.QuickAllocCaseAsync(hql1, Newtonsoft.Json.JsonConvert.SerializeObject(ids));



                };
                string hql = string.Format("select Count(*) {0} and c.Oper is null ", quickAllocHql);
                ser.GetCustomDataByHqlAsync(hql);
            }

        }
        /// <summary>
        /// 全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelAll_Click(object sender, RoutedEventArgs e)
        {
            dgdCase.SelectAll();
        }

        private void btnUnSelAll_Click(object sender, RoutedEventArgs e)
        {
            dgdCase.UnselectAll();
        }

        //进行快速分配的hql
        string quickAllocHql = string.Empty;

        private void btnUnDo_Click(object sender, RoutedEventArgs e)
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Allot_Case))
            {
                Tools.ShowMessage("您没有分配委案的权限", "", false);
                return;
            }

            if (dgdCase.SelectedItems.Count > 0)
            {
                IList<int> caseIds = new List<int>();
                foreach (var item in dgdCase.SelectedItems)
                {
                    DunLibrary.Dun.Case c = item as DunLibrary.Dun.Case;
                    if (c != null && c.Oper != null)
                    {
                        caseIds.Add(c.Id);
                    }
                }

                RadWindow.Confirm("此操作会撤销当前条件下所有案件的分配关系，请确认是否进行撤销？",
                    new EventHandler<WindowClosedEventArgs>((sender1, e1) =>
                    {
                        if (e1.DialogResult == true)
                        {
                            CaseService.CaseServiceClient ser = new CaseService.CaseServiceClient();
                            ser.UndoCaseAllocWithCaseIdsCompleted += (object sender2, CaseService.UndoCaseAllocWithCaseIdsCompletedEventArgs e2) =>
                            {
                                QueryPaging(queryCondition);
                                LoadOpersWithInfo();
                                Tools.ShowMessage(string.Format("成功撤销{0}条委案！", caseIds.Count), "", true);
                                return;

                            };
                            ser.UndoCaseAllocWithCaseIdsAsync(Newtonsoft.Json.JsonConvert.SerializeObject(caseIds));

                        }
                    }));
            }
            else
            {
                if (dgdCase.Items.Count == 0)
                {
                    Tools.ShowMessage("没有数据，请进行查询！", "", false);
                    return;
                }

                RadWindow.Confirm("此操作会撤销当前条件下所有案件的分配关系，请确认是否进行撤销？",
                    new EventHandler<WindowClosedEventArgs>((sender1, e1) =>
                        {
                            if (e1.DialogResult == true)
                            {
                                CaseService.CaseServiceClient ser = new CaseService.CaseServiceClient();
                                ser.UndoCaseAllocCompleted += (object sender2, CaseService.UndoCaseAllocCompletedEventArgs e2) =>
                                {
                                    int count = JsonSerializerHelper.JsonToEntity<int>(e2.Result);
                                    QueryPaging(queryCondition);
                                    LoadOpersWithInfo();
                                    Tools.ShowMessage(string.Format("成功撤销{0}条委案！", count), "", true);
                                    return;

                                };
                                string hql = string.Format("select c.Id {0}  ", quickAllocHql);
                                ser.UndoCaseAllocAsync(hql);

                            }
                        }));
            }
        }



    }

}
